import React, { useCallback, useEffect, useRef, useState } from 'react';
import { useParams, useNavigate, useSearchParams } from 'react-router-dom';
import { io } from "socket.io-client";
import { v4 as uuidv4 } from 'uuid';
import styles from './VideoConRoom.module.css';
import authManager from '../../utils/auth';
import type {
    User,
    Message,
    MediaStateChange,
    ScreenShareState,
    PeerConnection,
    RoomError
} from '../../types/video-conference';
// Socket.IO连接 - 连接到后端服务器
// 使用相对路径，通过 Vite 代理连接到后端（避免 Mixed Content 问题）
const socket = io({
    transports: ['websocket', 'polling'],
    reconnection: true,
    reconnectionDelay: 1000,
    reconnectionAttempts: 5
});

const peerConnections: Record<string, PeerConnection> = {};
// ICE candidate 队列，用于在远程描述设置前缓存 candidates
const iceCandidateQueues: Record<string, RTCIceCandidateInit[]> = {};

// 最大参与者数量
const MAX_PARTICIPANTS = 8;

// 处理 ICE candidate 队列的辅助函数
const processIceCandidateQueue = async (userId: string, pc: RTCPeerConnection) => {
    const queue = iceCandidateQueues[userId];
    if (queue && queue.length > 0 && pc.remoteDescription) {
        console.log(`📦 处理 ICE candidate 队列 [${userId}]: ${queue.length} 个候选`);
        for (const candidate of queue) {
            try {
                await pc.addIceCandidate(new RTCIceCandidate(candidate));
                console.log(`   ✅ 添加缓存的 ICE candidate`);
            } catch (error) {
                console.error(`   ❌ 添加缓存的 ICE candidate 失败:`, error);
            }
        }
        // 清空队列
        delete iceCandidateQueues[userId];
    }
};

// 添加 ICE candidate 的辅助函数（带队列机制）
const addIceCandidateSafely = async (userId: string, pc: RTCPeerConnection, candidate: RTCIceCandidateInit) => {
    if (!candidate) {
        return;
    }

    // 如果远程描述还没有设置，将 candidate 加入队列
    if (!pc.remoteDescription) {
        console.log(`📦 ICE candidate 加入队列 [${userId}]（远程描述尚未设置）`);
        if (!iceCandidateQueues[userId]) {
            iceCandidateQueues[userId] = [];
        }
        iceCandidateQueues[userId].push(candidate);
        return;
    }

    // 远程描述已设置，直接添加
    try {
        await pc.addIceCandidate(new RTCIceCandidate(candidate));
        console.log(`✅ 添加 ICE candidate 成功 [${userId}]`);
    } catch (error) {
        console.error(`❌ 添加 ICE candidate 失败 [${userId}]:`, error);
    }
};

// 远程视频组件 - 用于正确管理每个远程用户的视频流
const RemoteVideo: React.FC<{ userId: string; stream: MediaStream; user: User | undefined }> = ({ userId, stream, user }) => {
    const videoRef = useRef<HTMLVideoElement>(null);

    useEffect(() => {
        const videoEl = videoRef.current;
        if (!videoEl || !stream) return;

        console.log(`📺 设置远程视频元素 [${user?.name || userId}]:`, {
            streamId: stream.id,
            tracks: stream.getTracks().map(t => ({ id: t.id, kind: t.kind, enabled: t.enabled }))
        });

        // 确保视频元素绑定到正确的流
        if (videoEl.srcObject !== stream) {
            console.log(`   ✅ 绑定流到视频元素:`, stream.id);
            // ⭐ 先暂停当前播放，避免 AbortError
            if (videoEl.srcObject) {
                videoEl.pause();
                videoEl.srcObject = null;
            }
            // 设置新流
            videoEl.srcObject = stream;
        }

        // 确保视频轨道已启用
        stream.getTracks().forEach(track => {
            if (track.kind === 'video') {
                if (!track.enabled) {
                    console.warn(`   ⚠️ 视频轨道未启用:`, track.id);
                    track.enabled = true;
                }
                if (track.readyState !== 'live') {
                    console.warn(`   ⚠️ 视频轨道状态不是 live:`, track.id, track.readyState);
                }
            }
        });

        // ⭐ 延迟播放，确保流已经设置好
        const playVideo = () => {
            if (!videoEl || videoEl.srcObject !== stream) {
                console.log(`   ⚠️ 流已更改，取消播放 [${user?.name || userId}]`);
                return;
            }

            const playPromise = videoEl.play();
            if (playPromise !== undefined) {
                playPromise
                    .then(() => {
                        console.log(`   ✅ 视频播放成功 [${user?.name || userId}]`);
                    })
                    .catch(err => {
                        // AbortError 通常是流被替换导致的，不是真正的错误
                        if (err.name === 'AbortError') {
                            console.log(`   ℹ️ 播放请求被中断（可能是流更新）[${user?.name || userId}]`);
                        } else {
                            console.error(`   ❌ 播放远程视频失败 [${user?.name || userId}]:`, err);
                        }
                    });
            }
        };

        // ⭐ 额外检查：如果流有视频轨道但没有数据，尝试重新播放
        const checkAndRetry = () => {
            if (videoEl && videoEl.srcObject === stream) {
                const videoTracks = stream.getVideoTracks();
                if (videoTracks.length > 0 && videoTracks[0].readyState === 'live' && videoEl.paused) {
                    console.log(`   🔄 检测到视频轨道为live但视频暂停，尝试重新播放 [${user?.name || userId}]`);
                    playVideo();
                }
            }
        };

        // 等待元数据加载完成后再播放
        let timeout: NodeJS.Timeout | null = null;
        let retryInterval: NodeJS.Timeout | null = null;
        let retryCount = 0;

        if (videoEl.readyState >= 2) { // HAVE_CURRENT_DATA
            playVideo();
        } else {
            videoEl.addEventListener('loadedmetadata', playVideo, { once: true });
            // ⭐ 添加超时重试，防止元数据加载失败
            timeout = setTimeout(() => {
                if (videoEl.readyState < 2 && videoEl.srcObject === stream) {
                    console.log(`   ⚠️ 元数据加载超时，尝试直接播放 [${user?.name || userId}]`);
                    playVideo();
                }
            }, 2000);
        }

        // 定期检查并重试（最多5秒）
        retryInterval = setInterval(() => {
            if (retryCount++ < 5) {
                checkAndRetry();
            } else {
                if (retryInterval) {
                    clearInterval(retryInterval);
                    retryInterval = null;
                }
            }
        }, 1000);

        // 监听流的变化
        const handleTrackEnded = () => {
            console.log(`   ⚠️ 视频轨道已结束 [${user?.name || userId}]`);
        };

        stream.getTracks().forEach(track => {
            track.addEventListener('ended', handleTrackEnded);
        });

        return () => {
            // 清理
            stream.getTracks().forEach(track => {
                track.removeEventListener('ended', handleTrackEnded);
            });
            // ⭐ 清理定时器和间隔
            if (timeout) {
                clearTimeout(timeout);
            }
            if (retryInterval) {
                clearInterval(retryInterval);
            }
            if (videoEl) {
                // ⭐ 先暂停播放，避免 AbortError
                videoEl.pause();
                videoEl.removeEventListener('loadedmetadata', playVideo);
                videoEl.srcObject = null;
            }
        };
    }, [stream, userId, user]);

    // 监听流的轨道变化
    useEffect(() => {
        if (!stream) return;

        const handleTrackAdded = (event: MediaStreamTrackEvent) => {
            console.log(`   📹 新轨道已添加 [${user?.name || userId}]:`, event.track.kind);
        };

        const handleTrackRemoved = (event: MediaStreamTrackEvent) => {
            console.log(`   📹 轨道已移除 [${user?.name || userId}]:`, event.track.kind);
        };

        stream.addEventListener('addtrack', handleTrackAdded);
        stream.addEventListener('removetrack', handleTrackRemoved);

        return () => {
            stream.removeEventListener('addtrack', handleTrackAdded);
            stream.removeEventListener('removetrack', handleTrackRemoved);
        };
    }, [stream, userId, user]);

    const isVideoOn = user?.isVideoOn !== false;
    const hasVideoTracks = stream.getVideoTracks().length > 0;
    const videoEnabled = hasVideoTracks && stream.getVideoTracks()[0]?.enabled;

    return (
        <div className={styles.videoContainer}>
            <video
                ref={videoRef}
                autoPlay
                playsInline
                muted={false}
                className={styles.videoElement}
                style={{
                    // ⭐ 修复：始终显示视频元素，即使没有视频轨道也要显示（会显示黑屏但容器可见）
                    display: 'block',
                    width: '100%',
                    height: '100%',
                    objectFit: 'cover',
                    backgroundColor: '#000' // 确保黑屏时有黑色背景
                }}
                onLoadedMetadata={() => {
                    console.log(`   ✅ 视频元数据加载完成 [${user?.name || userId}]`);
                }}
                onError={(e) => {
                    console.error(`   ❌ 视频元素错误 [${user?.name || userId}]:`, e);
                }}
                onPlay={() => {
                    console.log(`   ▶️ 视频开始播放 [${user?.name || userId}]`);
                }}
                onPause={() => {
                    console.log(`   ⏸️ 视频暂停 [${user?.name || userId}]`);
                }}
            />
            {(!isVideoOn || !videoEnabled) && (
                <div className={styles.videoOffOverlay}>
                    📷
                    <span>视频已关闭</span>
                </div>
            )}
            <div className={styles.videoLabel}>
                {user ? user.name : `用户 ${userId.slice(0, 8)}`}
                {!hasVideoTracks && <span style={{ fontSize: '12px', opacity: 0.7 }}> (无视频)</span>}
            </div>
        </div>
    );
};

export default function VideoConRoom() {
    const { roomId } = useParams<{ roomId: string }>();
    const navigate = useNavigate();
    const [searchParams] = useSearchParams();
    const isHost = searchParams.get('isHost') === 'true';

    // 验证 roomId
    useEffect(() => {
        if (!roomId) {
            console.error('❌ 房间ID不存在，重定向到视频会议页面');
            navigate('/admin/video-conference');
            return;
        }
        console.log('✅ 当前房间ID:', roomId);
    }, [roomId, navigate]);
    const localVideoRef = useRef<HTMLVideoElement>(null);
    // 使用Map来存储每个用户的流，key是userId，value是MediaStream
    const [remoteStreamsMap, setRemoteStreamsMap] = useState<Record<string, MediaStream>>({});
    const [localStream, setLocalStream] = useState<MediaStream | null>(null);
    // 使用 ref 保存流，确保清理函数能访问到最新值
    const localStreamRef = useRef<MediaStream | null>(null);
    const screenStreamRef = useRef<MediaStream | null>(null);
    const [isVideoOn, setIsVideoOn] = useState(true);
    const [isAudioOn, setIsAudioOn] = useState(true);
    const [isScreenSharing, setIsScreenSharing] = useState(false);
    const [updateNewPeerWithScreenShare, setUpdateNewPeerWithScreenShare] = useState<((connection: RTCPeerConnection) => void) | null>(null);
    const [showLeaveModal, setShowLeaveModal] = useState(false);
    const [showUsersList, setShowUsersList] = useState(false);
    const [showChat, setShowChat] = useState(false);
    const [unreadCount, setUnreadCount] = useState(0);
    const [messages, setMessages] = useState<Message[]>([]);
    const [users, setUsers] = useState<User[]>([]);
    const chatInputRef = useRef<HTMLInputElement>(null);
    const messagesEndRef = useRef<HTMLDivElement>(null);
    const [screenStream, setScreenStream] = useState<MediaStream | null>(null);
    const localUserId = uuidv4();
    // 使用真实用户信息，如果未登录则使用随机用户名
    const currentUser = authManager.getUser();
    const localUserName = currentUser?.name || currentUser?.username || `用户${Math.floor(Math.random() * 1000)}`;
    const [showCopySuccess, setShowCopySuccess] = useState(false);
    const [errorMessage, setErrorMessage] = useState<string | null>(null);
    const [connectionErrors, setConnectionErrors] = useState<Record<string, string>>({});

    // ⭐ 通用的远程流检查函数 - 从所有连接中提取视频流
    // 使用 useRef 保存最新的 users，避免函数频繁重建
    const usersRef = useRef(users);
    useEffect(() => {
        usersRef.current = users;
    }, [users]);

    const checkAllRemoteStreams = useCallback(() => {
        console.log('🔍 全局检查所有连接的远程流...');
        Object.entries(peerConnections).forEach(([userId, { connection }]) => {
            const pc = connection;
            // ⭐ 从 ref 获取最新的 users，避免依赖 users 导致函数频繁重建
            const user = usersRef.current.find(u => u.id === userId);
            const userName = user?.name || userId.slice(0, 8);

            // 只检查已连接的 peer connection
            if (pc.connectionState !== 'connected' && pc.iceConnectionState !== 'connected') {
                console.log(`   ⏭️ 跳过未连接的连接 [${userName}]: ${pc.connectionState}`);
                return;
            }

            const receivers = pc.getReceivers();
            console.log(`   🔍 检查连接 [${userName}]: ${receivers.length} 个接收器`);

            if (receivers.length === 0) {
                console.log(`   ⚠️ 连接 [${userName}] 没有接收器`);
                return;
            }

            // 收集所有视频和音频轨道
            const videoTracks: MediaStreamTrack[] = [];
            const audioTracks: MediaStreamTrack[] = [];

            receivers.forEach((receiver) => {
                const track = receiver.track;
                if (track && track.readyState === 'live') {
                    if (track.kind === 'video') {
                        videoTracks.push(track);
                    } else if (track.kind === 'audio') {
                        audioTracks.push(track);
                    }
                }
            });

            // 如果有轨道，创建或更新流
            if (videoTracks.length > 0 || audioTracks.length > 0) {
                console.log(`   📹 发现 [${userName}]: ${videoTracks.length} 个视频轨道, ${audioTracks.length} 个音频轨道`);
                setRemoteStreamsMap(prev => {
                    const existingStream = prev[userId];
                    const allTracks = [...videoTracks, ...audioTracks];

                    // 检查是否需要更新流
                    const needsUpdate = !existingStream ||
                        existingStream.getTracks().length !== allTracks.length ||
                        !allTracks.every(track =>
                            existingStream.getTracks().some(et => et.id === track.id)
                        );

                    if (needsUpdate) {
                        const trackStream = new MediaStream(allTracks);
                        console.log(`   ✅ 创建/更新流 [${userName}]: ${trackStream.id}`);
                        return {
                            ...prev,
                            [userId]: trackStream
                        };
                    }
                    return prev;
                });
            } else {
                console.log(`   ⚠️ 连接 [${userName}] 没有有效的轨道`);
            }
        });
        // ⭐ 移除 users 依赖，使用 useRef 获取最新值，避免函数频繁重建导致 useEffect 重复执行
    }, []);

    // 复制会议链接到剪贴板
    const copyMeetingLink = async () => {
        if (!roomId) {
            alert('房间ID无效，无法复制链接');
            return;
        }
        try {
            const meetingUrl = `${window.location.origin}/admin/room/${roomId}`;
            console.log('📋 复制会议链接:', meetingUrl);
            await navigator.clipboard.writeText(meetingUrl);
            // 显示复制成功提示
            setShowCopySuccess(true);
            setTimeout(() => setShowCopySuccess(false), 2000);
        } catch (err) {
            console.error('复制链接失败:', err);
            // 降级方案：创建临时input元素来复制文本
            const textArea = document.createElement('textarea');
            textArea.value = `${window.location.origin}/admin/room/${roomId}`;
            document.body.appendChild(textArea);
            textArea.select();
            document.execCommand('copy');
            document.body.removeChild(textArea);
            // 显示复制成功提示
            setShowCopySuccess(true);
            setTimeout(() => setShowCopySuccess(false), 2000);
        }
    };

    useEffect(() => {
        const config = { iceServers: [{ urls: 'stun:stun.l.google.com:19302' }] };

        const start = async () => {
            try {
                // 1️⃣ 获取摄像头和麦克风
                const stream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true });
                setLocalStream(stream);
                localStreamRef.current = stream; // 保存到 ref
                if (localVideoRef.current) localVideoRef.current.srcObject = stream;

                // 2️⃣ 加入房间
                if (!roomId) {
                    console.error('❌ 房间ID无效，无法加入房间');
                    setErrorMessage('房间ID无效，请重新创建或加入会议');
                    setTimeout(() => {
                        navigate('/admin/video-conference');
                    }, 2000);
                    return;
                }
                console.log('🚪 加入房间:', roomId);
                socket.emit('join-room', {
                    roomId,
                    userId: localUserId,
                    userName: localUserName,
                    isHost: isHost
                });

                // 初始化本地用户信息
                setUsers([{
                    id: localUserId,
                    name: localUserName,
                    isVideoOn: true,
                    isAudioOn: true,
                    isScreenSharing: false,
                    isHost: isHost
                }]);

                // 3️⃣ 监听新成员加入
                socket.on('user-joined', async (userData: { userId: string; userName: string; users: User[] }) => {
                    console.log('🧍 用户列表更新:', userData.users.map(u => u.name).join(', '));
                    console.log('🧍 当前用户ID:', localUserId);
                    console.log('🧍 新加入的用户ID:', userData.userId);
                    setUsers(userData.users);

                    // 只为新加入的用户创建连接（不是为所有用户）
                    // 如果新加入的用户是自己，说明我们是新用户，等待其他人给我们发offer
                    // 如果新加入的用户是别人，说明我们是已存在的用户，应该主动创建连接
                    if (userData.userId === localUserId) {
                        console.log('✅ 我是新加入的用户，等待其他人发起连接');
                        // 为所有已存在的其他用户创建连接
                        for (const user of userData.users) {
                            if (user.id !== localUserId && !peerConnections[user.id]) {
                                console.log('🔗 为新用户（我）创建连接到已存在的用户:', user.name, user.id);

                                const pc = new RTCPeerConnection(config);
                                peerConnections[user.id] = { connection: pc, isScreenSharing: false };

                                pc.onconnectionstatechange = () => {
                                    const state = pc.connectionState;
                                    const iceState = pc.iceConnectionState;
                                    const signalingState = pc.signalingState;
                                    console.log(`🔗 连接状态 [${user.name}]:`, {
                                        connectionState: state,
                                        iceConnectionState: iceState,
                                        signalingState: signalingState,
                                        remoteDescription: !!pc.remoteDescription,
                                        localDescription: !!pc.localDescription
                                    });

                                    if (state === 'failed' || state === 'disconnected') {
                                        setConnectionErrors(prev => ({
                                            ...prev,
                                            [user.id]: `与 ${user.name} 的连接${state === 'failed' ? '失败' : '已断开'}`
                                        }));
                                    } else if (state === 'connected') {
                                        setConnectionErrors(prev => {
                                            const newErrors = { ...prev };
                                            delete newErrors[user.id];
                                            return newErrors;
                                        });
                                        console.log(`✅ 连接成功建立 [${user.name}]`);
                                        // ⭐ 连接成功后立即检查接收器，并启动定期检查
                                        checkExistingReceivers();
                                        setTimeout(() => checkExistingReceivers(), 300);
                                        setTimeout(() => checkExistingReceivers(), 800);
                                        startPeriodicCheck();
                                    }

                                    // 连接失败或断开时的处理
                                    if (state === 'failed' || state === 'disconnected' || state === 'closed') {
                                        stopPeriodicCheck();
                                    }

                                    // 当 ICE 连接状态改变时也记录
                                    if (iceState === 'failed') {
                                        console.error(`❌ ICE 连接失败 [${user.name}]`);
                                        stopPeriodicCheck();
                                    } else if (iceState === 'connected' || iceState === 'completed') {
                                        console.log(`✅ ICE 连接成功 [${user.name}]`);
                                        // ⭐ ICE 连接成功时也检查，并启动定期检查
                                        setTimeout(() => {
                                            checkExistingReceivers();
                                            startPeriodicCheck();
                                        }, 200);
                                    }
                                };

                                // ⭐ 连接成功后检查现有接收器的函数
                                const checkExistingReceivers = () => {
                                    const receivers = pc.getReceivers();
                                    console.log(`🔍 检查现有接收器 [${user.name}]:`, receivers.length);
                                    console.log(`   连接状态:`, {
                                        connectionState: pc.connectionState,
                                        iceConnectionState: pc.iceConnectionState,
                                        signalingState: pc.signalingState,
                                        hasRemoteDesc: !!pc.remoteDescription,
                                        hasLocalDesc: !!pc.localDescription
                                    });

                                    if (receivers.length === 0) {
                                        console.log(`   ⚠️ 暂无接收器 [${user.name}]，等待 ontrack 事件...`);
                                        return;
                                    }

                                    // 收集所有视频和音频轨道
                                    const videoTracks: MediaStreamTrack[] = [];
                                    const audioTracks: MediaStreamTrack[] = [];

                                    receivers.forEach((receiver) => {
                                        const track = receiver.track;
                                        if (track) {
                                            console.log(`   📡 接收器信息 [${user.name}]:`, {
                                                trackId: track.id,
                                                kind: track.kind,
                                                enabled: track.enabled,
                                                readyState: track.readyState,
                                                muted: track.muted
                                            });

                                            if (track.kind === 'video' && track.readyState === 'live') {
                                                videoTracks.push(track);
                                            } else if (track.kind === 'audio' && track.readyState === 'live') {
                                                audioTracks.push(track);
                                            }
                                        }
                                    });

                                    // 如果有视频轨道，创建或更新流
                                    if (videoTracks.length > 0) {
                                        console.log(`   📹 发现 ${videoTracks.length} 个视频接收器 [${user.name}]`);
                                        setRemoteStreamsMap(prev => {
                                            const existingStream = prev[user.id];
                                            // 检查是否需要更新流
                                            const needsUpdate = !existingStream ||
                                                !existingStream.getVideoTracks().some(t =>
                                                    videoTracks.some(vt => vt.id === t.id)
                                                );

                                            if (needsUpdate) {
                                                // 创建包含所有轨道的新流
                                                const allTracks = [...videoTracks, ...audioTracks];
                                                const trackStream = new MediaStream(allTracks);
                                                console.log(`   ✅ 从接收器创建流 [${user.name}]:`, trackStream.id, `包含 ${allTracks.length} 个轨道`);
                                                return {
                                                    ...prev,
                                                    [user.id]: trackStream
                                                };
                                            }
                                            console.log(`   ℹ️ 流已存在且包含这些轨道 [${user.name}]，跳过`);
                                            return prev;
                                        });
                                    } else {
                                        console.log(`   ⚠️ 没有有效的视频轨道 [${user.name}]`);
                                    }
                                };

                                // ⭐ 定期检查接收器（防止错过）
                                let receiverCheckInterval: NodeJS.Timeout | null = null;
                                const startPeriodicCheck = () => {
                                    if (receiverCheckInterval) return; // 已启动则跳过
                                    receiverCheckInterval = setInterval(() => {
                                        if (pc.connectionState === 'connected' || pc.iceConnectionState === 'connected') {
                                            checkExistingReceivers();
                                        } else {
                                            // 如果连接失败，停止检查
                                            if (receiverCheckInterval) {
                                                clearInterval(receiverCheckInterval);
                                                receiverCheckInterval = null;
                                            }
                                        }
                                    }, 1000); // 每秒检查一次
                                };

                                // 当连接建立时启动定期检查
                                const stopPeriodicCheck = () => {
                                    if (receiverCheckInterval) {
                                        clearInterval(receiverCheckInterval);
                                        receiverCheckInterval = null;
                                    }
                                };

                                // ⭐ 重要：先设置 ontrack 监听器，再添加轨道！
                                // 这样可以确保不会错过任何已到达的流
                                pc.ontrack = (e) => {
                                    console.log('📹 收到远程视频流:', user.name, '来自用户ID:', user.id);
                                    console.log('   ontrack 事件详情:', {
                                        streams: e.streams.length,
                                        track: e.track ? {
                                            id: e.track.id,
                                            kind: e.track.kind,
                                            enabled: e.track.enabled,
                                            readyState: e.track.readyState
                                        } : null,
                                        receiver: e.receiver ? { track: e.receiver.track?.kind } : null
                                    });

                                    // ⭐ 修复：优先从 streams[0] 获取，如果没有或为空，则从 track 创建流
                                    let remoteStream: MediaStream | null = null;

                                    if (e.streams && e.streams.length > 0 && e.streams[0].getTracks().length > 0) {
                                        // 使用 streams[0] 如果它包含轨道
                                        remoteStream = e.streams[0];
                                        console.log('   ✅ 从 streams[0] 获取流:', remoteStream.id);
                                    } else if (e.track) {
                                        // 如果没有流或流为空，从 track 创建新流
                                        remoteStream = new MediaStream([e.track]);
                                        console.log('   ✅ 从 track 创建新流:', remoteStream.id, '轨道类型:', e.track.kind);
                                    } else {
                                        // 尝试从接收器获取所有轨道
                                        const receivers = pc.getReceivers();
                                        const tracks: MediaStreamTrack[] = [];
                                        receivers.forEach(receiver => {
                                            if (receiver.track && receiver.track.readyState === 'live') {
                                                tracks.push(receiver.track);
                                            }
                                        });
                                        if (tracks.length > 0) {
                                            remoteStream = new MediaStream(tracks);
                                            console.log('   ✅ 从接收器创建流:', remoteStream.id, '包含', tracks.length, '个轨道');
                                        }
                                    }

                                    if (remoteStream && remoteStream.getTracks().length > 0) {
                                        console.log('   流的轨道:', remoteStream.getTracks().map(t => ({
                                            id: t.id,
                                            kind: t.kind,
                                            enabled: t.enabled,
                                            readyState: t.readyState,
                                            muted: t.muted
                                        })));
                                        setRemoteStreamsMap(prev => {
                                            // 检查是否已存在相同的流，避免重复
                                            const existingStream = prev[user.id];
                                            if (existingStream && existingStream.id === remoteStream!.id) {
                                                console.log('   ⚠️ 流已存在，跳过更新:', user.id);
                                                return prev;
                                            }
                                            // 强制更新，确保UI刷新
                                            console.log('   ✅ 更新远程流映射:', user.id, '流ID:', remoteStream!.id);
                                            console.log('   更新前的流映射:', Object.keys(prev));
                                            const newMap = {
                                                ...prev,
                                                [user.id]: remoteStream!
                                            };
                                            console.log('   更新后的流映射:', Object.keys(newMap));
                                            return newMap;
                                        });
                                    } else {
                                        console.warn('   ⚠️ 收到ontrack但无法创建有效流');
                                    }
                                };

                                // 添加本地轨道到连接
                                stream.getTracks().forEach(track => {
                                    console.log(`📤 添加本地轨道 [${user.name}]:`, track.kind, track.id);
                                    pc.addTrack(track, stream);
                                });

                                pc.onicecandidate = (e) => {
                                    if (e.candidate) {
                                        console.log('🧊 发送 ICE candidate 到:', user.id);
                                        socket.emit('ice-candidate', { roomId, to: user.id, candidate: e.candidate });
                                    }
                                };

                                try {
                                    // ⭐ 检查连接状态，确保在 stable 状态下创建 offer
                                    const initialState = pc.signalingState;
                                    console.log(`📝 准备创建 offer [${user.name}]...`);
                                    console.log(`   ⚠️ 创建前状态检查 - signalingState:`, initialState);

                                    if (initialState !== 'stable') {
                                        console.warn(`⚠️ 连接状态不是 stable [${user.name}]: ${initialState}，可能已有未完成的信令`);
                                        // 如果状态不是 stable，检查是否可以继续
                                        if (initialState !== 'have-local-offer') {
                                            console.error(`❌ 无法创建 offer，状态异常: ${initialState}`);
                                            return;
                                        }
                                    }

                                    const offer = await pc.createOffer({
                                        offerToReceiveAudio: true,
                                        offerToReceiveVideo: true
                                    });
                                    console.log(`✅ Offer 创建成功 [${user.name}]`);
                                    console.log(`   Offer 类型:`, offer.type);
                                    console.log(`   Offer SDP 长度:`, offer.sdp?.length || 0);

                                    // ⭐ 设置本地 offer 描述（状态应该变为 have-local-offer）
                                    console.log(`📝 设置本地描述 (offer) [${user.name}]...`);
                                    await pc.setLocalDescription(offer);
                                    console.log(`✅ 本地描述已设置 (offer) [${user.name}]`);
                                    console.log(`   设置后 signalingState:`, pc.signalingState);

                                    // ⭐ 验证状态转换：stable → have-local-offer
                                    if (pc.signalingState !== 'have-local-offer') {
                                        console.warn(`⚠️ 设置本地 offer 后状态不是 have-local-offer [${user.name}]:`, pc.signalingState);
                                    } else {
                                        console.log(`✅ 状态机转换完成: stable → have-local-offer [${user.name}]`);
                                    }

                                    // ⭐ 发送 offer 到信令服务器
                                    console.log('📤 发送 offer 到信令服务器:', user.name, user.id);
                                    socket.emit('offer', { roomId, to: user.id, offer });
                                    console.log(`✅ Offer 信令消息已发送 [${user.name}]`);
                                } catch (error) {
                                    console.error('❌ 创建 offer 失败:', error);
                                    console.error(`   错误详情:`, {
                                        name: (error as Error).name,
                                        message: (error as Error).message,
                                        currentState: pc.signalingState
                                    });
                                }
                            }
                        }
                    } else {
                        // 新加入的是其他人，我是已存在的用户
                        // ⭐ 修复：检查所有用户，为所有缺失连接的用户创建连接（包括新用户和可能遗漏的旧用户）
                        console.log('🔍 检查所有用户连接状态，当前peerConnections:', Object.keys(peerConnections));

                        for (const user of userData.users) {
                            if (user.id !== localUserId && !peerConnections[user.id]) {
                                const userId = user.id;
                                const userName = user.name;
                                const isNewUser = user.id === userData.userId;
                                console.log(`🔗 为用户创建连接: ${userName} (${userId}) ${isNewUser ? '(新加入)' : '(遗漏的用户)'}`);

                                const pc = new RTCPeerConnection(config);
                                peerConnections[userId] = { connection: pc, isScreenSharing: false };

                                // ⭐ 连接成功后检查现有接收器的函数
                                const checkExistingReceivers = () => {
                                    const receivers = pc.getReceivers();
                                    console.log(`🔍 检查现有接收器 [${userName}]:`, receivers.length);
                                    console.log(`   连接状态:`, {
                                        connectionState: pc.connectionState,
                                        iceConnectionState: pc.iceConnectionState,
                                        signalingState: pc.signalingState,
                                        hasRemoteDesc: !!pc.remoteDescription,
                                        hasLocalDesc: !!pc.localDescription
                                    });

                                    if (receivers.length === 0) {
                                        console.log(`   ⚠️ 暂无接收器 [${userName}]，等待 ontrack 事件...`);
                                        return;
                                    }

                                    // 收集所有视频和音频轨道
                                    const videoTracks: MediaStreamTrack[] = [];
                                    const audioTracks: MediaStreamTrack[] = [];

                                    receivers.forEach((receiver) => {
                                        const track = receiver.track;
                                        if (track) {
                                            console.log(`   📡 接收器信息 [${userName}]:`, {
                                                trackId: track.id,
                                                kind: track.kind,
                                                enabled: track.enabled,
                                                readyState: track.readyState,
                                                muted: track.muted
                                            });

                                            if (track.kind === 'video' && track.readyState === 'live') {
                                                videoTracks.push(track);
                                            } else if (track.kind === 'audio' && track.readyState === 'live') {
                                                audioTracks.push(track);
                                            }
                                        }
                                    });

                                    // 如果有视频轨道，创建或更新流
                                    if (videoTracks.length > 0) {
                                        console.log(`   📹 发现 ${videoTracks.length} 个视频接收器 [${userName}]`);
                                        setRemoteStreamsMap(prev => {
                                            const existingStream = prev[userId];
                                            // 检查是否需要更新流
                                            const needsUpdate = !existingStream ||
                                                !existingStream.getVideoTracks().some(t =>
                                                    videoTracks.some(vt => vt.id === t.id)
                                                );

                                            if (needsUpdate) {
                                                // 创建包含所有轨道的新流
                                                const allTracks = [...videoTracks, ...audioTracks];
                                                const trackStream = new MediaStream(allTracks);
                                                console.log(`   ✅ 从接收器创建流 [${userName}]:`, trackStream.id, `包含 ${allTracks.length} 个轨道`);
                                                return {
                                                    ...prev,
                                                    [userId]: trackStream
                                                };
                                            }
                                            console.log(`   ℹ️ 流已存在且包含这些轨道 [${userName}]，跳过`);
                                            return prev;
                                        });
                                    } else {
                                        console.log(`   ⚠️ 没有有效的视频轨道 [${userName}]`);
                                    }
                                };

                                // ⭐ 定期检查接收器（防止错过）
                                let receiverCheckInterval: NodeJS.Timeout | null = null;
                                const startPeriodicCheck = () => {
                                    if (receiverCheckInterval) return; // 已启动则跳过
                                    receiverCheckInterval = setInterval(() => {
                                        if (pc.connectionState === 'connected' || pc.iceConnectionState === 'connected') {
                                            checkExistingReceivers();
                                        } else {
                                            // 如果连接失败，停止检查
                                            if (receiverCheckInterval) {
                                                clearInterval(receiverCheckInterval);
                                                receiverCheckInterval = null;
                                            }
                                        }
                                    }, 1000); // 每秒检查一次
                                };

                                const stopPeriodicCheck = () => {
                                    if (receiverCheckInterval) {
                                        clearInterval(receiverCheckInterval);
                                        receiverCheckInterval = null;
                                    }
                                };

                                // ⭐ 监听 ICE 连接状态变化（比 connectionState 更早触发）
                                pc.oniceconnectionstatechange = () => {
                                    const iceState = pc.iceConnectionState;
                                    console.log(`🧊 ICE 连接状态变化 [${userName}]:`, iceState);
                                    if (iceState === 'connected' || iceState === 'completed') {
                                        console.log(`✅ ICE 已连接 [${userName}]，检查接收器...`);
                                        setTimeout(() => {
                                            checkExistingReceivers();
                                        }, 200);
                                        startPeriodicCheck();
                                    } else if (iceState === 'failed') {
                                        stopPeriodicCheck();
                                    }
                                };

                                // 监听连接状态
                                pc.onconnectionstatechange = () => {
                                    const state = pc.connectionState;
                                    const iceState = pc.iceConnectionState;
                                    const signalingState = pc.signalingState;
                                    console.log(`🔗 连接状态 [${userName}]:`, {
                                        connectionState: state,
                                        iceConnectionState: iceState,
                                        signalingState: signalingState,
                                        remoteDescription: !!pc.remoteDescription,
                                        localDescription: !!pc.localDescription
                                    });

                                    if (state === 'failed' || state === 'disconnected') {
                                        setConnectionErrors(prev => ({
                                            ...prev,
                                            [userId]: `与 ${userName} 的连接${state === 'failed' ? '失败' : '已断开'}`
                                        }));
                                        stopPeriodicCheck();
                                    } else if (state === 'connected') {
                                        setConnectionErrors(prev => {
                                            const newErrors = { ...prev };
                                            delete newErrors[userId];
                                            return newErrors;
                                        });
                                        console.log(`✅ 连接成功建立 [${userName}]`);
                                        // ⭐ 连接成功后，检查是否有遗漏的流
                                        setTimeout(() => {
                                            checkExistingReceivers();
                                        }, 500);
                                        startPeriodicCheck();
                                    } else if (state === 'closed') {
                                        stopPeriodicCheck();
                                    }

                                    if (iceState === 'failed') {
                                        console.error(`❌ ICE 连接失败 [${userName}]`);
                                        stopPeriodicCheck();
                                    } else if (iceState === 'connected') {
                                        console.log(`✅ ICE 连接成功 [${userName}]`);
                                        // ICE 连接成功时也检查
                                        setTimeout(() => {
                                            checkExistingReceivers();
                                        }, 300);
                                    }
                                };

                                // ⭐ 重要：先设置 ontrack 监听器
                                pc.ontrack = (e) => {
                                    console.log('📹 收到远程视频流:', userName, '来自用户ID:', userId);
                                    console.log('   ontrack 事件详情:', {
                                        streams: e.streams.length,
                                        track: e.track ? {
                                            id: e.track.id,
                                            kind: e.track.kind,
                                            enabled: e.track.enabled,
                                            readyState: e.track.readyState
                                        } : null
                                    });

                                    // ⭐ 修复：优先从 streams[0] 获取，如果没有或为空，则从 track 创建流
                                    let remoteStream: MediaStream | null = null;

                                    if (e.streams && e.streams.length > 0 && e.streams[0].getTracks().length > 0) {
                                        // 使用 streams[0] 如果它包含轨道
                                        remoteStream = e.streams[0];
                                        console.log('   ✅ 从 streams[0] 获取流:', remoteStream.id);
                                    } else if (e.track) {
                                        // 如果没有流或流为空，从 track 创建新流
                                        remoteStream = new MediaStream([e.track]);
                                        console.log('   ✅ 从 track 创建新流:', remoteStream.id, '轨道类型:', e.track.kind);
                                    } else {
                                        // 尝试从接收器获取所有轨道
                                        const receivers = pc.getReceivers();
                                        const tracks: MediaStreamTrack[] = [];
                                        receivers.forEach(receiver => {
                                            if (receiver.track && receiver.track.readyState === 'live') {
                                                tracks.push(receiver.track);
                                            }
                                        });
                                        if (tracks.length > 0) {
                                            remoteStream = new MediaStream(tracks);
                                            console.log('   ✅ 从接收器创建流:', remoteStream.id, '包含', tracks.length, '个轨道');
                                        }
                                    }

                                    if (remoteStream && remoteStream.getTracks().length > 0) {
                                        console.log('   流的轨道:', remoteStream.getTracks().map(t => ({
                                            id: t.id,
                                            kind: t.kind,
                                            enabled: t.enabled,
                                            readyState: t.readyState,
                                            muted: t.muted
                                        })));
                                        setRemoteStreamsMap(prev => {
                                            // 检查是否已存在相同的流，避免重复
                                            const existingStream = prev[userId];
                                            if (existingStream && existingStream.id === remoteStream!.id) {
                                                console.log('   ⚠️ 流已存在，跳过更新:', userId);
                                                return prev;
                                            }
                                            // 强制更新，确保UI刷新
                                            console.log('   ✅ 更新远程流映射:', userId, '流ID:', remoteStream!.id);
                                            console.log('   更新前的流映射:', Object.keys(prev));
                                            const newMap = {
                                                ...prev,
                                                [userId]: remoteStream!
                                            };
                                            console.log('   更新后的流映射:', Object.keys(newMap));
                                            return newMap;
                                        });
                                    } else {
                                        console.warn('   ⚠️ 收到ontrack但无法创建有效流');
                                    }
                                };

                                // 添加本地轨道到连接
                                stream.getTracks().forEach(track => {
                                    console.log(`📤 添加本地轨道 [${userName}]:`, track.kind, track.id);
                                    pc.addTrack(track, stream);
                                });

                                pc.onicecandidate = (e) => {
                                    if (e.candidate) {
                                        console.log('🧊 发送 ICE candidate 到:', userId);
                                        socket.emit('ice-candidate', { roomId, to: userId, candidate: e.candidate });
                                    }
                                };

                                try {
                                    // ⭐ 检查连接状态，确保在 stable 状态下创建 offer
                                    const initialState = pc.signalingState;
                                    console.log(`📝 准备创建 offer [${userName}]...`);
                                    console.log(`   ⚠️ 创建前状态检查 - signalingState:`, initialState);

                                    if (initialState !== 'stable') {
                                        console.warn(`⚠️ 连接状态不是 stable [${userName}]: ${initialState}，可能已有未完成的信令`);
                                        if (initialState !== 'have-local-offer') {
                                            console.error(`❌ 无法创建 offer，状态异常: ${initialState}`);
                                            return;
                                        }
                                    }

                                    const offer = await pc.createOffer({
                                        offerToReceiveAudio: true,
                                        offerToReceiveVideo: true
                                    });
                                    console.log(`✅ Offer 创建成功 [${userName}]`);
                                    console.log(`   Offer 类型:`, offer.type);
                                    console.log(`   Offer SDP 长度:`, offer.sdp?.length || 0);

                                    // ⭐ 设置本地 offer 描述（状态应该变为 have-local-offer）
                                    console.log(`📝 设置本地描述 (offer) [${userName}]...`);
                                    await pc.setLocalDescription(offer);
                                    console.log(`✅ 本地描述已设置 (offer) [${userName}]`);
                                    console.log(`   设置后 signalingState:`, pc.signalingState);

                                    // ⭐ 验证状态转换：stable → have-local-offer
                                    if (pc.signalingState !== 'have-local-offer') {
                                        console.warn(`⚠️ 设置本地 offer 后状态不是 have-local-offer [${userName}]:`, pc.signalingState);
                                    } else {
                                        console.log(`✅ 状态机转换完成: stable → have-local-offer [${userName}]`);
                                    }

                                    // ⭐ 发送 offer 到信令服务器
                                    console.log('📤 发送 offer 到信令服务器:', userName, userId);
                                    socket.emit('offer', { roomId, to: userId, offer });
                                    console.log(`✅ Offer 信令消息已发送 [${userName}]`);
                                } catch (error) {
                                    console.error('❌ 创建 offer 失败:', error);
                                    console.error(`   错误详情:`, {
                                        name: (error as Error).name,
                                        message: (error as Error).message,
                                        currentState: pc.signalingState
                                    });
                                }
                            }
                        }
                    }
                });

                // 4️⃣ 收到 offer
                socket.on('offer', async ({ from, offer }) => {
                    console.log('📩 收到 offer 来自:', from);

                    // 检查连接是否存在
                    let pc: RTCPeerConnection;
                    if (peerConnections[from]) {
                        pc = peerConnections[from].connection;
                        // ⭐ 如果连接已存在但远程描述还没设置，继续处理
                        if (pc.remoteDescription) {
                            console.log('⚠️ 已存在连接且远程描述已设置，跳过:', from);
                            return;
                        }
                        console.log('⚠️ 连接已存在但远程描述未设置，继续处理 offer:', from);
                    } else {
                        // 创建新连接
                        pc = new RTCPeerConnection(config);
                        peerConnections[from] = { connection: pc, isScreenSharing: false };

                        // 设置 ontrack 监听器（在添加轨道之前）
                        pc.ontrack = (e) => {
                            console.log('📹 收到远程视频流来自:', from);
                            console.log('   ontrack 事件详情:', {
                                streams: e.streams.length,
                                track: e.track ? {
                                    id: e.track.id,
                                    kind: e.track.kind,
                                    enabled: e.track.enabled,
                                    readyState: e.track.readyState
                                } : null
                            });
                            if (e.streams && e.streams.length > 0) {
                                const remoteStream = e.streams[0];
                                console.log('   流的轨道:', remoteStream.getTracks().map(t => ({
                                    id: t.id,
                                    kind: t.kind,
                                    enabled: t.enabled,
                                    readyState: t.readyState
                                })));
                                setRemoteStreamsMap(prev => {
                                    if (prev[from] === remoteStream) {
                                        console.log('   ⚠️ 流已存在，跳过更新:', from);
                                        return prev;
                                    }
                                    console.log('   ✅ 更新远程流映射:', from, '流ID:', remoteStream.id);
                                    return {
                                        ...prev,
                                        [from]: remoteStream
                                    };
                                });
                            }
                        };

                        // 添加本地轨道
                        const activeStream = isScreenSharing && screenStream ? screenStream : stream;
                        activeStream.getTracks().forEach(track => {
                            console.log(`📤 添加本地轨道 [${from}]:`, track.kind, track.id);
                            pc.addTrack(track, activeStream);
                        });
                        
                        // 检查是否需要应用屏幕共享轨道更新
                        if (updateNewPeerWithScreenShare) {
                            console.log(`📤 应用屏幕共享轨道更新到新连接 [${from}]`);
                            updateNewPeerWithScreenShare(pc);
                        }

                        // 监听 ICE candidate
                        pc.onicecandidate = (e) => {
                            if (e.candidate) {
                                console.log('🧊 发送 ICE candidate 到:', from);
                                socket.emit('ice-candidate', { roomId, to: from, candidate: e.candidate });
                            }
                        };
                    }

                    // ⭐ 如果连接已存在，确保监听器已设置
                    if (!pc.ontrack) {
                        pc.ontrack = (e) => {
                            console.log('📹 收到远程视频流来自:', from);
                            console.log('   ontrack 事件详情:', {
                                streams: e.streams.length,
                                track: e.track ? {
                                    id: e.track.id,
                                    kind: e.track.kind,
                                    enabled: e.track.enabled,
                                    readyState: e.track.readyState
                                } : null
                            });

                            // ⭐ 修复：优先从 streams[0] 获取，如果没有或为空，则从 track 创建流
                            let remoteStream: MediaStream | null = null;

                            if (e.streams && e.streams.length > 0 && e.streams[0].getTracks().length > 0) {
                                // 使用 streams[0] 如果它包含轨道
                                remoteStream = e.streams[0];
                                console.log('   ✅ 从 streams[0] 获取流:', remoteStream.id);
                            } else if (e.track) {
                                // 如果没有流或流为空，从 track 创建新流
                                remoteStream = new MediaStream([e.track]);
                                console.log('   ✅ 从 track 创建新流:', remoteStream.id, '轨道类型:', e.track.kind);
                            } else {
                                // 尝试从接收器获取所有轨道
                                const receivers = pc.getReceivers();
                                const tracks: MediaStreamTrack[] = [];
                                receivers.forEach(receiver => {
                                    if (receiver.track && receiver.track.readyState === 'live') {
                                        tracks.push(receiver.track);
                                    }
                                });
                                if (tracks.length > 0) {
                                    remoteStream = new MediaStream(tracks);
                                    console.log('   ✅ 从接收器创建流:', remoteStream.id, '包含', tracks.length, '个轨道');
                                }
                            }

                            if (remoteStream && remoteStream.getTracks().length > 0) {
                                console.log('   流的轨道:', remoteStream.getTracks().map(t => ({
                                    id: t.id,
                                    kind: t.kind,
                                    enabled: t.enabled,
                                    readyState: t.readyState
                                })));
                                setRemoteStreamsMap(prev => {
                                    const existingStream = prev[from];
                                    if (existingStream && existingStream.id === remoteStream!.id) {
                                        console.log('   ⚠️ 流已存在，跳过更新:', from);
                                        return prev;
                                    }
                                    console.log('   ✅ 更新远程流映射:', from, '流ID:', remoteStream!.id);
                                    return {
                                        ...prev,
                                        [from]: remoteStream!
                                    };
                                });
                            } else {
                                console.warn('   ⚠️ 收到ontrack但无法创建有效流');
                            }
                        };
                    }

                    // ⭐ 如果连接已存在，确保本地轨道已添加
                    const activeStream = isScreenSharing && screenStream ? screenStream : stream;
                    const existingSenders = pc.getSenders();
                    const hasVideoTrack = existingSenders.some(s => s.track?.kind === 'video');
                    const hasAudioTrack = existingSenders.some(s => s.track?.kind === 'audio');

                    if (!hasVideoTrack || !hasAudioTrack) {
                        activeStream.getTracks().forEach(track => {
                            const hasTrack = existingSenders.some(s => s.track?.id === track.id);
                            if (!hasTrack) {
                                console.log(`📤 添加本地轨道 [${from}]:`, track.kind, track.id);
                                pc.addTrack(track, activeStream);
                            }
                        });
                    }

                    // ⭐ 确保 ICE candidate 监听器已设置
                    if (!pc.onicecandidate) {
                        pc.onicecandidate = (e) => {
                            if (e.candidate) {
                                console.log('🧊 发送 ICE candidate 到:', from);
                                socket.emit('ice-candidate', { roomId, to: from, candidate: e.candidate });
                            }
                        };
                    }

                    // ⭐ 连接成功后，检查是否已有接收器（可能 ontrack 在连接成功前已触发）
                    const checkExistingReceivers = () => {
                        const receivers = pc.getReceivers();
                        console.log(`🔍 检查现有接收器 [${from}]:`, receivers.length);
                        console.log(`   连接状态:`, {
                            connectionState: pc.connectionState,
                            iceConnectionState: pc.iceConnectionState,
                            signalingState: pc.signalingState,
                            hasRemoteDesc: !!pc.remoteDescription,
                            hasLocalDesc: !!pc.localDescription
                        });

                        if (receivers.length === 0) {
                            console.log(`   ⚠️ 暂无接收器 [${from}]，等待 ontrack 事件...`);
                            return;
                        }

                        // 收集所有视频和音频轨道
                        const videoTracks: MediaStreamTrack[] = [];
                        const audioTracks: MediaStreamTrack[] = [];

                        receivers.forEach((receiver) => {
                            const track = receiver.track;
                            if (track) {
                                console.log(`   📡 接收器信息 [${from}]:`, {
                                    trackId: track.id,
                                    kind: track.kind,
                                    enabled: track.enabled,
                                    readyState: track.readyState,
                                    muted: track.muted
                                });

                                if (track.kind === 'video' && track.readyState === 'live') {
                                    videoTracks.push(track);
                                } else if (track.kind === 'audio' && track.readyState === 'live') {
                                    audioTracks.push(track);
                                }
                            }
                        });

                        // 如果有视频轨道，创建或更新流
                        if (videoTracks.length > 0) {
                            console.log(`   📹 发现 ${videoTracks.length} 个视频接收器 [${from}]`);
                            setRemoteStreamsMap(prev => {
                                const existingStream = prev[from];
                                // 检查是否需要更新流
                                const needsUpdate = !existingStream ||
                                    !existingStream.getVideoTracks().some(t =>
                                        videoTracks.some(vt => vt.id === t.id)
                                    );

                                if (needsUpdate) {
                                    // 创建包含所有轨道的新流
                                    const allTracks = [...videoTracks, ...audioTracks];
                                    const trackStream = new MediaStream(allTracks);
                                    console.log(`   ✅ 从接收器创建流 [${from}]:`, trackStream.id, `包含 ${allTracks.length} 个轨道`);
                                    return {
                                        ...prev,
                                        [from]: trackStream
                                    };
                                }
                                console.log(`   ℹ️ 流已存在且包含这些轨道 [${from}]，跳过`);
                                return prev;
                            });
                        } else {
                            console.log(`   ⚠️ 没有有效的视频轨道 [${from}]`);
                        }
                    };

                    // ⭐ 定期检查接收器（防止错过）
                    let receiverCheckInterval: NodeJS.Timeout | null = null;
                    const startPeriodicCheck = () => {
                        if (receiverCheckInterval) return; // 已启动则跳过
                        receiverCheckInterval = setInterval(() => {
                            if (pc.connectionState === 'connected' || pc.iceConnectionState === 'connected') {
                                checkExistingReceivers();
                            } else {
                                // 如果连接失败，停止检查
                                if (receiverCheckInterval) {
                                    clearInterval(receiverCheckInterval);
                                    receiverCheckInterval = null;
                                }
                            }
                        }, 1000); // 每秒检查一次
                    };

                    const stopPeriodicCheck = () => {
                        if (receiverCheckInterval) {
                            clearInterval(receiverCheckInterval);
                            receiverCheckInterval = null;
                        }
                    };

                    // ⭐ 设置连接状态监听器和接收器检查（统一的处理函数）
                    const setupConnectionHandlers = () => {
                        // 连接状态变化处理
                        const handleConnectionStateChange = () => {
                            const state = pc.connectionState;
                            const iceState = pc.iceConnectionState;
                            const signalingState = pc.signalingState;
                            console.log(`🔗 连接状态 [${from}]:`, {
                                connectionState: state,
                                iceConnectionState: iceState,
                                signalingState: signalingState,
                                remoteDescription: !!pc.remoteDescription,
                                localDescription: !!pc.localDescription
                            });

                            if (state === 'failed' || state === 'disconnected') {
                                setConnectionErrors(prev => ({
                                    ...prev,
                                    [from]: `连接${state === 'failed' ? '失败' : '已断开'}`
                                }));
                                stopPeriodicCheck();
                            } else if (state === 'connected') {
                                setConnectionErrors(prev => {
                                    const newErrors = { ...prev };
                                    delete newErrors[from];
                                    return newErrors;
                                });
                                console.log(`✅ 连接成功建立 [${from}]`);
                                // ⭐ 连接成功后立即检查接收器，并启动定期检查
                                checkExistingReceivers();
                                setTimeout(() => checkExistingReceivers(), 300);
                                setTimeout(() => checkExistingReceivers(), 800);
                                startPeriodicCheck();
                            }

                            if (iceState === 'failed') {
                                console.error(`❌ ICE 连接失败 [${from}]`);
                                stopPeriodicCheck();
                            } else if (iceState === 'connected' || iceState === 'completed') {
                                console.log(`✅ ICE 连接成功 [${from}]`);
                                // ⭐ ICE 连接成功时也检查，并启动定期检查
                                setTimeout(() => {
                                    checkExistingReceivers();
                                    startPeriodicCheck();
                                }, 200);
                            }
                        };

                        // 只在没有设置时添加监听器
                        if (!pc.onconnectionstatechange) {
                            pc.onconnectionstatechange = handleConnectionStateChange;
                        }

                        // ICE 连接状态监听（更早触发）
                        if (!pc.oniceconnectionstatechange) {
                            pc.oniceconnectionstatechange = () => {
                                const iceState = pc.iceConnectionState;
                                console.log(`🧊 ICE 连接状态变化 [${from}]:`, iceState);
                                if (iceState === 'connected' || iceState === 'completed') {
                                    console.log(`✅ ICE 已连接 [${from}]，检查接收器...`);
                                    setTimeout(() => {
                                        checkExistingReceivers();
                                        startPeriodicCheck();
                                    }, 200);
                                }
                            };
                        }
                    };

                    setupConnectionHandlers();

                    try {
                        // ⭐ 检查连接状态，如果已经设置过远程描述，跳过
                        const currentState = pc.signalingState;
                        console.log(`📝 收到 offer 来自 [${from}]，当前 signalingState:`, currentState);

                        // ⭐ 严格检查：只有在 stable 状态下才能处理新的 offer
                        if (currentState !== 'stable') {
                            console.log(`⚠️ 连接状态异常 [${from}]: ${currentState}，期望 'stable'，跳过处理`);
                            // 如果已经有本地描述，说明可能已经处理过，只是状态不对，跳过
                            if (pc.localDescription) {
                                console.log(`⚠️ 连接 [${from}] 已有本地描述，跳过重复的 offer`);
                                await processIceCandidateQueue(from, pc);
                            }
                            return;
                        }

                        // 如果已经有远程描述，说明已经处理过这个 offer
                        if (pc.remoteDescription) {
                            console.log(`⚠️ 连接 [${from}] 已经有远程描述，可能是重复的 offer，跳过`);
                            // 处理队列中的 ICE candidates（以防万一）
                            await processIceCandidateQueue(from, pc);
                            return;
                        }

                        // 如果已经有本地描述，说明已经在处理另一个 offer/answer，跳过
                        if (pc.localDescription) {
                            console.log(`⚠️ 连接 [${from}] 已经有本地描述，可能正在处理其他信令，跳过`);
                            await processIceCandidateQueue(from, pc);
                            return;
                        }

                        console.log(`📝 设置远程描述 (offer) [${from}]...`);
                        console.log(`   Offer 类型:`, offer.type);
                        console.log(`   Offer SDP 长度:`, offer.sdp?.length || 0);
                        await pc.setRemoteDescription(new RTCSessionDescription(offer));
                        console.log(`✅ 远程描述已设置 (offer) [${from}]`);
                        console.log(`   设置后 signalingState:`, pc.signalingState);

                        // ⭐ 验证状态是否正确 - 必须在 have-remote-offer 状态
                        if (pc.signalingState !== 'have-remote-offer') {
                            const errorMsg = `设置远程描述后状态不正确 [${from}]: 期望 'have-remote-offer'，实际 '${pc.signalingState}'`;
                            console.error(`❌ ${errorMsg}`);
                            throw new Error(errorMsg);
                        }
                        console.log(`✅ 状态验证通过: have-remote-offer [${from}]`);

                        // ⭐ 设置远程描述后，处理队列中的 ICE candidates（必须先处理，再创建 answer）
                        await processIceCandidateQueue(from, pc);
                        console.log(`✅ ICE candidates 队列处理完成 [${from}]`);

                        // ⭐ 设置远程描述后立即检查接收器（可能在创建 answer 前就有流）
                        setTimeout(() => {
                            checkExistingReceivers();
                        }, 100);

                        // ⭐ 关键步骤：创建 answer（必须在 have-remote-offer 状态下）
                        console.log(`📝 准备创建 answer [${from}]...`);
                        console.log(`   ⚠️ 创建前状态检查 - signalingState:`, pc.signalingState);

                        // 再次验证状态，确保在正确的状态下创建 answer
                        if (pc.signalingState !== 'have-remote-offer') {
                            const errorMsg = `创建 answer 前状态不正确 [${from}]: 期望 'have-remote-offer'，实际 '${pc.signalingState}'`;
                            console.error(`❌ ${errorMsg}`);
                            throw new Error(errorMsg);
                        }

                        const answer = await pc.createAnswer({
                            offerToReceiveAudio: true,
                            offerToReceiveVideo: true
                        });
                        console.log(`✅ Answer 创建成功 [${from}]`);
                        console.log(`   Answer 类型:`, answer.type);
                        console.log(`   Answer SDP 长度:`, answer.sdp?.length || 0);
                        console.log(`   创建后（设置前）signalingState:`, pc.signalingState);

                        // ⭐ 再次验证状态，确保可以设置本地描述（状态应该仍然是 have-remote-offer）
                        const stateBeforeSetLocal = pc.signalingState;
                        if (stateBeforeSetLocal !== 'have-remote-offer') {
                            // 如果状态已经是 stable 且有本地描述，说明已经设置过了，跳过
                            if (stateBeforeSetLocal === 'stable' && pc.localDescription) {
                                console.log(`⚠️ 连接 [${from}] 状态已是 stable 且有本地描述，跳过重复设置`);
                                // 仍然发送 answer（以防对方没收到）
                                socket.emit('answer', { roomId, to: from, answer });
                                return;
                            }
                            const errorMsg = `创建 answer 后状态不正确 [${from}]: 期望 'have-remote-offer'，实际 '${stateBeforeSetLocal}'`;
                            console.error(`❌ ${errorMsg}`);
                            throw new Error(errorMsg);
                        }

                        // ⭐ 检查是否已经有本地描述（防止并发问题）
                        if (pc.localDescription) {
                            console.log(`⚠️ 连接 [${from}] 已有本地描述，跳过重复设置`);
                            // 仍然发送 answer（以防对方没收到）
                            socket.emit('answer', { roomId, to: from, answer });
                            return;
                        }

                        // ⭐ 关键步骤：设置本地 answer 描述（状态应该变为 stable）
                        console.log(`📝 设置本地描述 (answer) [${from}]...`);
                        try {
                            await pc.setLocalDescription(answer);
                            console.log(`✅ 本地描述已设置 (answer) [${from}]`);
                            const finalState = pc.signalingState;
                            console.log(`   设置后 signalingState:`, finalState);

                            // ⭐ 验证最终状态应该是 stable
                            if (finalState !== 'stable') {
                                console.warn(`⚠️ 设置本地 answer 后状态不是 stable [${from}]:`, finalState);
                            } else {
                                console.log(`✅ 状态机转换完成: have-remote-offer → stable [${from}]`);
                            }
                        } catch (setLocalError) {
                            // 如果状态已经是 stable，说明可能在其他地方已经设置过了
                            const error = setLocalError as Error;
                            const currentState = pc.signalingState;
                            const hasLocalDesc = !!pc.localDescription;
                            if (error.name === 'InvalidStateError' && currentState === 'stable' && hasLocalDesc) {
                                console.log(`⚠️ 连接 [${from}] 已在 stable 状态且有本地描述，跳过设置`);
                                // 继续发送 answer，不影响后续流程
                            } else {
                                // 其他错误需要抛出
                                throw error;
                            }
                        }

                        // ⭐ 发送 answer 到信令服务器
                        console.log('📤 发送 answer 到信令服务器:', from);
                        socket.emit('answer', { roomId, to: from, answer });
                        console.log(`✅ Answer 信令消息已发送 [${from}]`);
                    } catch (error) {
                        console.error(`❌ 处理 offer 失败 [${from}]:`, error);
                        console.error(`   错误详情:`, {
                            name: (error as Error).name,
                            message: (error as Error).message,
                            stack: (error as Error).stack,
                            currentState: pc.signalingState,
                            hasRemoteDesc: !!pc.remoteDescription,
                            hasLocalDesc: !!pc.localDescription
                        });
                        setConnectionErrors(prev => ({
                            ...prev,
                            [from]: `处理连接请求失败: ${(error as Error).message}`
                        }));
                    }

                    // ⭐ 创建 answer 后再次检查
                    setTimeout(() => {
                        checkExistingReceivers();
                    }, 200);
                });

                // 5️⃣ 收到 answer
                socket.on('answer', async ({ from, answer }) => {
                    console.log('📩 收到 answer 来自:', from);
                    console.log(`   Answer 类型:`, answer.type);
                    console.log(`   Answer SDP 长度:`, answer.sdp?.length || 0);
                    const peerConn = peerConnections[from];
                    if (peerConn) {
                        try {
                            const pc = peerConn.connection;
                            const currentState = pc.signalingState;
                            console.log(`📝 收到 answer 来自 [${from}]，当前 signalingState:`, currentState);

                            // ⭐ 检查连接状态，只有在 have-local-offer 状态下才能设置远程 answer
                            console.log(`📝 收到 answer 信令消息 [${from}]，状态检查...`);
                            console.log(`   当前 signalingState:`, currentState);
                            console.log(`   hasRemoteDesc:`, !!pc.remoteDescription);
                            console.log(`   hasLocalDesc:`, !!pc.localDescription);

                            if (currentState !== 'have-local-offer') {
                                console.log(`⚠️ 连接状态异常 [${from}]: ${currentState}，无法设置远程 answer`);
                                console.log(`   当前状态详情:`, {
                                    signalingState: currentState,
                                    hasRemoteDesc: !!pc.remoteDescription,
                                    hasLocalDesc: !!pc.localDescription,
                                    connectionState: pc.connectionState,
                                    iceConnectionState: pc.iceConnectionState
                                });

                                // 如果已经是 stable，说明可能已经完成过交换，跳过
                                if (currentState === 'stable') {
                                    console.log(`⚠️ 连接已稳定，可能是重复的 answer 消息 [${from}]`);
                                    // 处理队列中的 ICE candidates（以防万一）
                                    await processIceCandidateQueue(from, pc);
                                    return;
                                }

                                // 如果是 have-remote-offer，说明已经收到过 offer 但还没处理完，不应该收到 answer
                                if (currentState === 'have-remote-offer') {
                                    console.error(`❌ 状态冲突 [${from}]: 处于 have-remote-offer 但收到了 answer，信令消息可能乱序`);
                                    return;
                                }

                                // 其他状态也跳过，等待正确的状态
                                console.log(`⚠️ 跳过 answer，等待正确的状态 [${from}]`);
                                return;
                            }

                            console.log(`✅ 状态验证通过: have-local-offer [${from}]`);

                            // 如果已经有远程描述，可能是重复的 answer
                            if (pc.remoteDescription) {
                                console.log(`⚠️ 连接 [${from}] 已经有远程描述，可能是重复的 answer，跳过`);
                                await processIceCandidateQueue(from, pc);
                                return;
                            }

                            // ⭐ 在执行前再次检查状态（防止并发问题）
                            const stateBeforeSet = pc.signalingState;
                            if (stateBeforeSet !== 'have-local-offer') {
                                if (stateBeforeSet === 'stable' && pc.remoteDescription) {
                                    console.log(`⚠️ 连接 [${from}] 已在 stable 状态且有远程描述，跳过重复设置`);
                                    await processIceCandidateQueue(from, pc);
                                    return;
                                }
                                console.log(`⚠️ 状态在检查后已改变 [${from}]: ${stateBeforeSet}，期望 'have-local-offer'，跳过`);
                                return;
                            }

                            console.log(`📝 设置远程描述 (answer) [${from}]...`);
                            console.log(`   设置前 signalingState:`, stateBeforeSet);
                            console.log(`   设置前 hasRemoteDesc:`, !!pc.remoteDescription);
                            console.log(`   设置前 hasLocalDesc:`, !!pc.localDescription);

                            // ⭐ 关键步骤：设置远程 answer 描述（状态应该从 have-local-offer 变为 stable）
                            try {
                                await pc.setRemoteDescription(new RTCSessionDescription(answer));
                                console.log('✅ 设置远程描述成功:', from);
                                const finalState = pc.signalingState;
                                console.log(`   设置后 signalingState:`, finalState);

                                // ⭐ 验证状态转换：have-local-offer → stable
                                if (finalState !== 'stable') {
                                    console.warn(`⚠️ 设置远程 answer 后状态不是 stable [${from}]:`, finalState);
                                } else {
                                    console.log(`✅ 状态机转换完成: have-local-offer → stable [${from}]`);
                                }

                                // 设置远程描述后，处理队列中的 ICE candidates
                                await processIceCandidateQueue(from, pc);

                                // ⭐ 设置远程描述后，检查是否已有接收器（可能 ontrack 已触发但被错过）
                                setTimeout(() => {
                                    const receivers = peerConn.connection.getReceivers();
                                    console.log(`🔍 设置 answer 后检查接收器 [${from}]:`, receivers.length);
                                    receivers.forEach((receiver) => {
                                        const track = receiver.track;
                                        if (track && track.kind === 'video') {
                                            console.log(`   📹 发现视频接收器 [${from}]:`, track.id);
                                            setRemoteStreamsMap(prev => {
                                                if (!prev[from]) {
                                                    const trackStream = new MediaStream([track]);
                                                    console.log(`   ✅ 从接收器创建流 [${from}]:`, trackStream.id);
                                                    return {
                                                        ...prev,
                                                        [from]: trackStream
                                                    };
                                                }
                                                return prev;
                                            });
                                        }
                                    });
                                }, 200);
                            } catch (setRemoteError) {
                                const error = setRemoteError as Error;
                                const currentState = pc.signalingState;
                                const hasRemoteDesc = !!pc.remoteDescription;

                                // 如果是 InvalidStateError 且状态已经是 stable，说明可能已经在其他地方处理过了
                                if (error.name === 'InvalidStateError' && currentState === 'stable' && hasRemoteDesc) {
                                    console.log(`⚠️ 连接 [${from}] 已在 stable 状态且有远程描述，可能是重复的 answer，跳过`);
                                    // 处理队列中的 ICE candidates（以防万一）
                                    await processIceCandidateQueue(from, pc);
                                } else {
                                    console.error('❌ 设置远程描述失败:', error, from);
                                    console.error('   错误详情:', {
                                        name: error.name,
                                        message: error.message,
                                        currentState: currentState,
                                        hasRemoteDesc: hasRemoteDesc,
                                        hasLocalDesc: !!pc.localDescription
                                    });
                                }
                            }
                        } catch (error) {
                            console.error('❌ 处理 answer 时发生错误:', error, from);
                        }
                    } else {
                        console.warn('⚠️ 未找到对应的 peerConnection:', from);
                    }
                });

                // 6️⃣ 收到 ICE
                socket.on('ice-candidate', async ({ from, candidate }) => {
                    console.log('🧊 收到 ICE candidate 来自:', from);
                    const peerConn = peerConnections[from];
                    if (peerConn && candidate) {
                        await addIceCandidateSafely(from, peerConn.connection, candidate);
                    } else {
                        console.warn('⚠️ 未找到对应的 peerConnection 或 candidate 为空:', from);
                    }
                });

                // 7️⃣ 用户离开
                socket.on('user-left', (data: { userId: string; users: User[] }) => {
                    console.log('👋 用户离开:', data.userId);
                    // 移除对应的对等连接
                    if (peerConnections[data.userId]) {
                        peerConnections[data.userId].connection.close();
                        delete peerConnections[data.userId];
                    }
                    // 清理对应的 ICE candidate 队列
                    if (iceCandidateQueues[data.userId]) {
                        delete iceCandidateQueues[data.userId];
                    }
                    // 移除对应的远程流
                    setRemoteStreamsMap(prev => {
                        const newMap = { ...prev };
                        if (newMap[data.userId]) {
                            // 停止流的轨道
                            newMap[data.userId].getTracks().forEach(track => track.stop());
                            delete newMap[data.userId];
                        }
                        return newMap;
                    });
                    // 更新用户列表
                    setUsers(data.users);
                });

                // 8️⃣ 监听聊天消息
                socket.on('chat-message', (data: { message: Message }) => {
                    setMessages(prev => {
                        const newMessages = [...prev, data.message];
                        // 保存到本地存储（最多保存100条）
                        const historyKey = `chat-history-${roomId}`;
                        const messagesToSave = newMessages.slice(-100);
                        localStorage.setItem(historyKey, JSON.stringify(messagesToSave));
                        return newMessages;
                    });
                    // 如果聊天面板未打开，增加未读消息计数
                    if (!showChat) {
                        setUnreadCount(prev => prev + 1);
                    }
                });

                // 9️⃣ 监听媒体状态变化
                socket.on('media-state-change', (data: MediaStateChange) => {
                    setUsers(prev => prev.map(user =>
                        user.id === data.userId
                            ? {
                                ...user,
                                isVideoOn: data.isVideoOn !== undefined ? data.isVideoOn : user.isVideoOn,
                                isAudioOn: data.isAudioOn !== undefined ? data.isAudioOn : user.isAudioOn
                            }
                            : user
                    ));
                });

                // 🔟 监听屏幕共享状态变化
                socket.on('screen-share-state', (data: ScreenShareState) => {
                    console.log('📱 接收到屏幕共享状态更新:', data);
                    setUsers(prev => prev.map(user =>
                        user.id === data.userId
                            ? { ...user, isScreenSharing: data.isScreenSharing }
                            : user
                    ));
                    
                    // 如果有用户开始屏幕共享，可以添加视觉提示
                    if (data.isScreenSharing) {
                        console.log(`👤 用户 ${data.userId} 开始屏幕共享`);
                        // 可以在这里添加通知或其他UI反馈
                    } else {
                        console.log(`👤 用户 ${data.userId} 停止屏幕共享`);
                    }
                });

                // 1️⃣1️⃣ 监听房间错误
                socket.on('room-error', (error: RoomError) => {
                    console.error('❌ 房间错误:', error);
                    setErrorMessage(error.message);
                    if (error.type === 'room-full') {
                        setTimeout(() => {
                            navigate('/admin/video-conference');
                        }, 3000);
                    } else if (error.type === 'room-not-found') {
                        setTimeout(() => {
                            navigate('/admin/video-conference');
                        }, 3000);
                    }
                });

                // 1️⃣2️⃣ 监听连接错误
                socket.on('connect_error', (error) => {
                    console.error('Socket连接错误:', error);
                    setErrorMessage('无法连接到服务器，请检查网络连接');
                });

                // 1️⃣3️⃣ 加载聊天历史记录
                const loadChatHistory = () => {
                    const historyKey = `chat-history-${roomId}`;
                    const history = localStorage.getItem(historyKey);
                    if (history) {
                        try {
                            const messages = JSON.parse(history);
                            // 恢复消息时间戳
                            const restoredMessages = messages.map((msg: any) => ({
                                ...msg,
                                timestamp: new Date(msg.timestamp)
                            }));
                            setMessages(restoredMessages);
                        } catch (e) {
                            console.error('加载聊天历史失败:', e);
                        }
                    }
                };
                loadChatHistory();
            } catch (error) {
                console.error('获取媒体设备失败:', error);
                setErrorMessage('无法访问摄像头或麦克风，请检查权限设置。');
            }
        };

        start();

        // 清理函数
        return () => {
            console.log('🧹 组件卸载，开始清理媒体流和连接...');

            // 清理本地视频流
            if (localStreamRef.current) {
                console.log('🛑 停止本地视频流');
                localStreamRef.current.getTracks().forEach(track => {
                    track.stop();
                    console.log(`   ✓ 已停止 ${track.kind} track: ${track.id}`);
                });
                localStreamRef.current = null;
            }

            // 清理屏幕共享流
            if (screenStreamRef.current) {
                console.log('🛑 停止屏幕共享流');
                screenStreamRef.current.getTracks().forEach(track => {
                    track.stop();
                    console.log(`   ✓ 已停止 ${track.kind} track: ${track.id}`);
                });
                screenStreamRef.current = null;
            }

            // 清空视频元素的 srcObject
            if (localVideoRef.current) {
                localVideoRef.current.srcObject = null;
                console.log('🧹 清空本地视频元素');
            }

            // 移除所有 socket 监听器
            socket.off('user-joined');
            socket.off('offer');
            socket.off('answer');
            socket.off('ice-candidate');
            socket.off('user-left');
            socket.off('chat-message');
            socket.off('media-state-change');
            socket.off('screen-share-state');
            console.log('🔌 移除所有 socket 监听器');

            // 通知服务器离开房间
            socket.emit('leave-room', { roomId, userId: localUserId });
            console.log('👋 发送离开房间消息');

            // 关闭所有对等连接
            Object.values(peerConnections).forEach(pc => {
                pc.connection.close();
                console.log('🔌 关闭对等连接');
            });
            // 清空对等连接对象和 ICE candidate 队列
            Object.keys(peerConnections).forEach(key => delete peerConnections[key]);
            Object.keys(iceCandidateQueues).forEach(key => delete iceCandidateQueues[key]);

            console.log('✅ 清理完成');
        };
    }, [roomId]);

    // ⭐ 定期检查所有远程流（确保捕获所有连接中的流）
    useEffect(() => {
        if (Object.keys(peerConnections).length === 0) {
            return;
        }

        // 立即检查一次
        checkAllRemoteStreams();

        // 设置定期检查（每2秒检查一次）
        const interval = setInterval(() => {
            checkAllRemoteStreams();
        }, 2000);

        return () => {
            clearInterval(interval);
        };
        // ⭐ 修复：移除 users 依赖，只依赖 checkAllRemoteStreams
        // users 的变化已经在 checkAllRemoteStreams 内部通过闭包处理
    }, [checkAllRemoteStreams]);

    // 切换视频状态
    const toggleVideo = () => {
        if (localStream) {
            const videoTracks = localStream.getVideoTracks();
            videoTracks.forEach(track => {
                track.enabled = !track.enabled;
            });
            setIsVideoOn(!isVideoOn);
            // 通知其他用户视频状态变化
            socket.emit('media-state-change', {
                roomId,
                userId: localUserId,
                isVideoOn: !isVideoOn
            });
            // 更新本地用户信息
            setUsers(prev => prev.map(user =>
                user.id === localUserId
                    ? { ...user, isVideoOn: !isVideoOn }
                    : user
            ));
        }
    };

    // 切换音频状态
    const toggleAudio = () => {
        if (localStream) {
            const audioTracks = localStream.getAudioTracks();
            audioTracks.forEach(track => {
                track.enabled = !track.enabled;
            });
            setIsAudioOn(!isAudioOn);
            // 通知其他用户音频状态变化
            socket.emit('media-state-change', {
                roomId,
                userId: localUserId,
                isAudioOn: !isAudioOn
            });
            // 更新本地用户信息
            setUsers(prev => prev.map(user =>
                user.id === localUserId
                    ? { ...user, isAudioOn: !isAudioOn }
                    : user
            ));
        }
    };

    // 切换屏幕共享
    const toggleScreenShare = async () => {
        try {
            if (isScreenSharing && screenStream) {
                // 停止屏幕共享
                console.log('📱 停止屏幕共享...');
                screenStream.getTracks().forEach(track => {
                    track.stop();
                    console.log(`   ✓ 已停止 ${track.kind} track: ${track.id}`);
                });
                setScreenStream(null);
                screenStreamRef.current = null; // 清空 ref
                setIsScreenSharing(false);

                // 恢复使用摄像头视频
                if (localStream) {
                    console.log('🔄 恢复摄像头视频流');
                    // 重新发送摄像头视频给所有连接的用户
                    Object.entries(peerConnections).forEach(([userId, { connection }]) => {
                        try {
                            // 使用replaceTrack方法更高效地切换轨道
                            const senders = connection.getSenders();
                            senders.forEach(sender => {
                                if (sender.track?.kind === 'video') {
                                    const videoTrack = localStream.getVideoTracks()[0];
                                    if (videoTrack) {
                                        console.log(`🔄 为用户 ${userId} 替换为摄像头视频轨道`);
                                        sender.replaceTrack(videoTrack);
                                    }
                                }
                                if (sender.track?.kind === 'audio') {
                                    const audioTrack = localStream.getAudioTracks()[0];
                                    if (audioTrack) {
                                        sender.replaceTrack(audioTrack);
                                    }
                                }
                            });
                        } catch (error) {
                            console.error(`❌ 为用户 ${userId} 恢复摄像头视频失败:`, error);
                            // 备用方案：移除并重新添加轨道
                            try {
                                // 移除旧的视频轨道
                                connection.getSenders().forEach(sender => {
                                    if (sender.track?.kind === 'video') {
                                        connection.removeTrack(sender);
                                    }
                                });
                                // 添加新的摄像头视频轨道
                                localStream.getTracks().forEach(track => {
                                    connection.addTrack(track, localStream);
                                });
                            } catch (fallbackError) {
                                console.error(`❌ 备用方案也失败:`, fallbackError);
                            }
                        }
                    });
                }
            } else {
                // 开始屏幕共享
                console.log('📱 请求屏幕共享权限...');
                const newScreenStream = await navigator.mediaDevices.getDisplayMedia({
                    video: {
                        cursor: 'always',
                        displaySurface: 'monitor',
                        logicalSurface: true,
                        width: { ideal: 1920, max: 1920 },
                        height: { ideal: 1080, max: 1080 },
                        frameRate: { ideal: 30, max: 60 }
                    } as MediaTrackConstraints,
                    audio: true // 允许共享系统音频
                });

                console.log('✅ 成功获取屏幕共享流，轨道数量:', newScreenStream.getTracks().length);
                const videoTrack = newScreenStream.getVideoTracks()[0];
                const audioTrack = newScreenStream.getAudioTracks()[0];

                if (!videoTrack) {
                    throw new Error('未获取到屏幕共享视频轨道');
                }

                // 监听屏幕共享停止事件
                videoTrack.onended = () => {
                    console.log('📱 用户停止了屏幕共享');
                    toggleScreenShare();
                };

                setScreenStream(newScreenStream);
                screenStreamRef.current = newScreenStream; // 保存到 ref
                setIsScreenSharing(true);

                // 发送屏幕共享视频给所有连接的用户
                console.log('🔄 发送屏幕共享给所有连接的用户');
                Object.entries(peerConnections).forEach(([userId, { connection }]) => {
                    try {
                        // 使用replaceTrack方法更高效地切换轨道
                        const senders = connection.getSenders();
                        senders.forEach(sender => {
                            if (sender.track?.kind === 'video') {
                                console.log(`🔄 为用户 ${userId} 替换为屏幕共享视频轨道`);
                                sender.replaceTrack(videoTrack);
                            }
                            if (sender.track?.kind === 'audio' && audioTrack) {
                                console.log(`🔄 为用户 ${userId} 替换为屏幕共享音频轨道`);
                                sender.replaceTrack(audioTrack);
                            }
                        });
                    } catch (error) {
                        console.error(`❌ 为用户 ${userId} 设置屏幕共享失败:`, error);
                        // 备用方案：移除并重新添加轨道
                        try {
                            // 移除旧的视频轨道
                            connection.getSenders().forEach(sender => {
                                if (sender.track?.kind === 'video') {
                                    connection.removeTrack(sender);
                                }
                            });
                            // 添加新的屏幕共享视频轨道
                            newScreenStream.getTracks().forEach(track => {
                                connection.addTrack(track, newScreenStream);
                            });
                        } catch (fallbackError) {
                            console.error(`❌ 备用方案也失败:`, fallbackError);
                        }
                    }
                });

                // 为新加入的用户准备屏幕共享轨道更新函数
                const updateNewPeerWithScreenShare = (newConnection: RTCPeerConnection) => {
                    try {
                        console.log('🔄 为新加入用户设置屏幕共享');
                        const senders = newConnection.getSenders();
                        senders.forEach(sender => {
                            if (sender.track?.kind === 'video' && videoTrack) {
                                sender.replaceTrack(videoTrack);
                            }
                            if (sender.track?.kind === 'audio' && audioTrack) {
                                sender.replaceTrack(audioTrack);
                            }
                        });
                    } catch (error) {
                        console.error('❌ 为新用户设置屏幕共享失败:', error);
                    }
                };
                
                // 保存更新新对等连接的函数，以便在新用户加入时使用
                setUpdateNewPeerWithScreenShare(updateNewPeerWithScreenShare);
            }

            // 通知其他用户屏幕共享状态变化
            socket.emit('screen-share-state', {
                roomId,
                userId: localUserId,
                isScreenSharing: !isScreenSharing
            });
            console.log(`📢 通知其他用户屏幕共享状态: ${!isScreenSharing}`);

            // 更新本地用户信息
            setUsers(prev => prev.map(user =>
                user.id === localUserId
                    ? { ...user, isScreenSharing: !isScreenSharing }
                    : user
            ));
        } catch (error) {
            console.error('❌ 屏幕共享失败:', error);
            // 提供更详细的错误信息
            let errorMessage = '无法开始屏幕共享';
            if ((error as Error).name === 'NotAllowedError') {
                errorMessage += '：用户拒绝了屏幕共享请求';
            } else if ((error as Error).name === 'NotFoundError') {
                errorMessage += '：未找到可用的屏幕共享源';
            } else if ((error as Error).name === 'NotReadableError') {
                errorMessage += '：屏幕共享源当前不可访问';
            } else if ((error as Error).name === 'SecurityError') {
                errorMessage += '：由于安全原因，屏幕共享被阻止';
            }
            alert(`${errorMessage}，请确保浏览器支持并已授予权限。`);
        }
    };

    // 发送聊天消息
    const sendMessage = () => {
        if (chatInputRef.current && chatInputRef.current.value.trim()) {
            const newMessage: Message = {
                id: uuidv4(),
                senderId: localUserId,
                senderName: localUserName,
                content: chatInputRef.current.value.trim(),
                timestamp: new Date()
            };

            // 发送消息到服务器
            socket.emit('chat-message', {
                roomId,
                message: newMessage
            });

            // 添加到本地消息列表
            setMessages(prev => [...prev, newMessage]);

            // 清空输入框
            chatInputRef.current.value = '';
        }
    };

    // 处理聊天输入框回车事件
    const handleChatKeyPress = (e: React.KeyboardEvent) => {
        if (e.key === 'Enter') {
            sendMessage();
        }
    };

    // 自动滚动到最新消息
    useEffect(() => {
        messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
    }, [messages]);

    // 显示退出会议确认框
    const handleLeaveMeeting = () => {
        setShowLeaveModal(true);
    };
    // 确认退出会议
    const confirmLeaveMeeting = () => {
        setShowLeaveModal(false);
        console.log('👋 确认退出会议，开始清理...');

        // 清理媒体流（使用 ref 确保访问最新值）
        if (localStreamRef.current) {
            console.log('🛑 停止本地视频流');
            localStreamRef.current.getTracks().forEach(track => {
                track.stop();
                console.log(`   ✓ 已停止 ${track.kind} track: ${track.id}`);
            });
            localStreamRef.current = null;
        }

        if (screenStreamRef.current) {
            console.log('🛑 停止屏幕共享流');
            screenStreamRef.current.getTracks().forEach(track => {
                track.stop();
                console.log(`   ✓ 已停止 ${track.kind} track: ${track.id}`);
            });
            screenStreamRef.current = null;
        }

        // 清空视频元素的 srcObject
        if (localVideoRef.current) {
            localVideoRef.current.srcObject = null;
            console.log('🧹 清空本地视频元素');
        }

        // 清理远程流的所有轨道
        Object.values(remoteStreamsMap).forEach(stream => {
            stream.getTracks().forEach(track => track.stop());
        });
        setRemoteStreamsMap({});
        console.log('🧹 清理远程流');

        // 移除所有 socket 监听器
        socket.off('user-joined');
        socket.off('offer');
        socket.off('answer');
        socket.off('ice-candidate');
        socket.off('user-left');
        socket.off('chat-message');
        socket.off('media-state-change');
        socket.off('screen-share-state');
        console.log('🔌 移除所有 socket 监听器');

        // 清除聊天历史记录
        if (roomId) {
            // 可选：离开时保留历史记录，或者清除
            // localStorage.removeItem(`chat-history-${roomId}`);
        }

        // 通知服务器离开房间
        socket.emit('leave-room', { roomId, userId: localUserId });
        console.log('👋 发送离开房间消息');

        // 关闭所有对等连接
        Object.values(peerConnections).forEach(pc => {
            pc.connection.close();
        });
        // 清空对等连接对象和 ICE candidate 队列
        Object.keys(peerConnections).forEach(key => delete peerConnections[key]);
        Object.keys(iceCandidateQueues).forEach(key => delete iceCandidateQueues[key]);
        console.log('🔌 关闭所有对等连接');

        // 清空状态
        setLocalStream(null);
        setScreenStream(null);

        console.log('✅ 清理完成，导航回主页');
        // 导航回视频会议主页面
        navigate('/admin/video-conference');
    };

    // 取消退出会议
    const cancelLeaveMeeting = () => {
        setShowLeaveModal(false);
    };

    return (
        <div className={styles.container}>
            <header className={styles.header}>
                <div className={styles.headerInfo}>
                    <h2>会议 ID: {roomId || '加载中...'}</h2>
                    <p>参会人数: {users.length} / {MAX_PARTICIPANTS}</p>
                    {isHost && <span className={styles.hostBadge}>👑 主持人</span>}
                </div>
                {errorMessage && (
                    <div className={styles.errorMessage}>
                        ⚠️ {errorMessage}
                        <button onClick={() => setErrorMessage(null)} className={styles.closeError}>×</button>
                    </div>
                )}
                {Object.keys(connectionErrors).length > 0 && (
                    <div className={styles.connectionErrors}>
                        {Object.values(connectionErrors).map((error, idx) => (
                            <div key={idx} className={styles.connectionError}>⚠️ {error}</div>
                        ))}
                    </div>
                )}
                <div className={styles.headerButtons}>
                    <button
                        onClick={() => setShowUsersList(!showUsersList)}
                        className={styles.userListButton}
                        title="参会成员"
                    >
                        👥
                    </button>
                    <button
                        onClick={() => {
                            setShowChat(!showChat);
                            // 打开聊天面板时重置未读消息计数
                            if (!showChat) {
                                setUnreadCount(0);
                            }
                        }}
                        className={styles.chatButton}
                    >
                        💬{unreadCount > 0 && <span className={styles.unreadBadge}>{unreadCount}</span>}
                    </button>
                    <button
                        onClick={copyMeetingLink}
                        className={styles.shareButton}
                        title="分享会议链接"
                    >
                        🔗
                    </button>
                    <button
                        onClick={handleLeaveMeeting}
                        className={styles.leaveButton}
                    >
                        🚪
                    </button>
                </div>
                {showCopySuccess && (
                    <div className={styles.copySuccessToast}>
                        会议链接已复制到剪贴板！
                    </div>
                )}
            </header>

            <main className={styles.main}>
                <div className={styles.videoGrid}>
                    {/* 本地视频 */}
                    <div className={styles.videoContainer}>
                        <video
                            ref={localVideoRef}
                            autoPlay
                            playsInline
                            className={styles.videoElement}
                            style={{ display: isVideoOn ? 'block' : 'none' }}
                        />
                        {!isVideoOn && (
                            <div className={styles.videoOffOverlay}>
                                📷
                                <span>视频已关闭</span>
                            </div>
                        )}
                        <div className={styles.videoLabel}>
                            {localUserName} (我)
                        </div>
                    </div>

                    {/* 远程视频 - 使用remoteStreamsMap来正确映射用户和流 */}
                    {(() => {
                        const remoteUsers = users.filter(u => u.id !== localUserId);
                        const hasRemoteStreams = Object.entries(remoteStreamsMap).length > 0;
                        const connectedUserIds = new Set(Object.keys(peerConnections));

                        // 调试信息
                        console.log('🎬 渲染视频网格:', {
                            remoteUsers: remoteUsers.length,
                            remoteStreams: Object.keys(remoteStreamsMap).length,
                            peerConnections: Object.keys(peerConnections).length,
                            streamMap: Object.keys(remoteStreamsMap),
                            userList: remoteUsers.map(u => u.id)
                        });

                        if (hasRemoteStreams) {
                            // 确保没有重复的 userId，使用 Set 去重
                            const uniqueUserIds = Array.from(new Set(Object.keys(remoteStreamsMap)));
                            console.log('🔍 去重后的用户ID:', uniqueUserIds, '原始映射:', Object.keys(remoteStreamsMap));

                            return uniqueUserIds.map((userId) => {
                                const stream = remoteStreamsMap[userId];
                                if (!stream) {
                                    console.warn(`⚠️ 用户 ${userId} 的流不存在`);
                                    return null;
                                }

                                // 查找对应的远程用户信息
                                const remoteUser = users.find(user => user.id === userId);
                                console.log(`🎥 渲染远程视频:`, userId, remoteUser?.name, '流ID:', stream.id, '流轨道数:', stream.getTracks().length);
                                // 使用 userId + stream.id 确保 key 唯一
                                return (
                                    <RemoteVideo
                                        key={`remote-video-${userId}-${stream.id}`}
                                        userId={userId}
                                        stream={stream}
                                        user={remoteUser}
                                    />
                                );
                            }).filter(Boolean); // 过滤掉 null 值
                        } else if (remoteUsers.length > 0) {
                            // 如果没有远程流，显示等待信息和连接状态
                            return (
                                <div className={styles.waitingContainer}>
                                    <div className={styles.waitingMessage}>
                                        <div className={styles.waitingSpinner}>⏳</div>
                                        <p>等待其他用户连接...</p>
                                        <p className={styles.waitingHint}>
                                            已检测到 {remoteUsers.length} 个其他用户
                                        </p>
                                        <p className={styles.waitingHint}>
                                            已建立连接: {connectedUserIds.size} / {remoteUsers.length}
                                        </p>
                                        <p className={styles.waitingHint} style={{ fontSize: '12px', marginTop: '10px' }}>
                                            用户列表: {remoteUsers.map(u => u.name).join(', ')}
                                        </p>
                                        <p className={styles.waitingHint} style={{ fontSize: '12px' }}>
                                            连接状态: {Object.entries(peerConnections).map(([uid, pc]) => {
                                                const user = remoteUsers.find(u => u.id === uid);
                                                return `${user?.name || uid}: ${pc.connection.connectionState}`;
                                            }).join('; ') || '无'}
                                        </p>
                                    </div>
                                </div>
                            );
                        }
                        return null;
                    })()}
                </div>
            </main>

            {/* 控制栏 */}
            <footer className={styles.controls}>
                <button
                    onClick={toggleVideo}
                    className={`${styles.controlButton} ${isVideoOn ? styles.videoButtonOn : styles.videoButtonOff}`}
                >
                    {isVideoOn ? '📹' : '📷'}
                </button>
                <button
                    onClick={toggleAudio}
                    className={`${styles.controlButton} ${isAudioOn ? styles.audioButtonOn : styles.audioButtonOff}`}
                >
                    {isAudioOn ? '🔊' : '🔇'}
                </button>
                <button
                    onClick={toggleScreenShare}
                    className={`${styles.controlButton} ${isScreenSharing ? styles.screenButtonOn : styles.screenButtonOff}`}
                >
                    {isScreenSharing ? '🛑' : '🖥️'}
                </button>
            </footer>
            {/* 用户列表面板 */}
            {showUsersList && (
                <div className={`${styles.usersPanel} ${showUsersList ? styles.open : ''}`}>
                    <div className={styles.panelHeader}>
                        <h3>参会成员</h3>
                        <button onClick={() => setShowUsersList(false)} className={styles.closeButton}>×</button>
                    </div>
                    <div className={styles.usersList}>
                        {users.map(user => (
                            <div key={user.id} className={`${styles.userItem} ${user.id === localUserId ? styles.me : ''}`}>
                                <div className={styles.userInfo}>
                                    <span className={styles.userName}>
                                        {user.name}
                                        {user.id === localUserId && <span className={styles.localUserTag}> (我)</span>}
                                        {user.isHost && <span className={styles.hostTag}>👑</span>}
                                    </span>
                                    <div className={styles.userStatus}>
                                        {user.isAudioOn ? '🔊' : '🔇'} {user.isVideoOn ? '📹' : '📷'}
                                        {user.isScreenSharing && ' 🖥️'}
                                    </div>
                                </div>
                            </div>
                        ))}
                    </div>
                </div>
            )}

            {/* 聊天面板 */}
            {showChat && (
                <div className={`${styles.chatPanel} ${showChat ? styles.open : ''}`}>
                    <div className={styles.chatPanelHeader}>
                        <h3>聊天</h3>
                        <button onClick={() => setShowChat(false)} className={styles.closeButton}>×</button>
                    </div>
                    <div className={styles.messagesList}>
                        {messages.map(message => (
                            <div
                                key={message.id}
                                className={`${styles.message} ${message.senderId === localUserId ? styles.myMessage : styles.otherMessage}`}
                            >
                                {message.senderId !== localUserId && (
                                    <div className={styles.messageSender}>{message.senderName}</div>
                                )}
                                <div className={styles.messageContent}>{message.content}</div>
                                <div className={styles.messageTime}>
                                    {new Date(message.timestamp).toLocaleTimeString()}
                                </div>
                            </div>
                        ))}
                        <div ref={messagesEndRef} />
                    </div>
                    <div className={styles.chatInputContainer}>
                        <input
                            ref={chatInputRef}
                            type="text"
                            placeholder="输入消息..."
                            className={styles.chatInput}
                            onKeyPress={handleChatKeyPress}
                        />
                        <button onClick={sendMessage} className={styles.sendButton}>发送</button>
                    </div>
                </div>
            )}

            {/* 退出会议确认弹窗 */}
            {showLeaveModal && (
                <div className={styles.modalOverlay}>
                    <div className={styles.modalContent}>
                        <h3 className={styles.modalTitle}>确认退出会议？</h3>
                        <p className={styles.modalMessage}>您确定要离开当前会议吗？</p>
                        <div className={styles.modalActions}>
                            <button
                                onClick={cancelLeaveMeeting}
                                className={`${styles.modalButton} ${styles.cancelButton}`}
                            >
                                取消
                            </button>
                            <button
                                onClick={confirmLeaveMeeting}
                                className={`${styles.modalButton} ${styles.confirmButton}`}
                            >
                                确认退出
                            </button>
                        </div>
                    </div>
                </div>
            )}

            {/* 背景遮罩 */}
            {(showUsersList || showChat) && (
                <div
                    className={`${styles.overlay} ${(showUsersList || showChat) ? styles.active : ''}`}
                    onClick={() => {
                        setShowUsersList(false);
                        setShowChat(false);
                        // 关闭聊天面板时重置未读消息计数
                        setUnreadCount(0);
                    }}
                />
            )}
        </div>
    );
}
